<?php

/**
 * @copyright        2017 opencart.cn - All Rights Reserved
 * @author:          Sam Chen <sam.chen@opencart.cn>
 * @created:         2017-10-23 10:41:19
 * @modified by:     Sam Chen <sam.chen@opencart.cn>
 * @modified:        2017-10-30 15:27:16
 */

abstract class GDModuleBaseController extends Controller {
  protected $module_code = '';
  protected $validation_rules = [];
  private $error = array();

  public function index() {
    $this->beforeIndex();
    $this->document->addScript('view/javascript/vue/vue.min.js');
    $this->document->addScript('view/javascript/vue/vue-resource.min.js');
    $this->document->addStyle('view/stylesheet/gd-module.css');

    $this->load->model('extension/module');

    $data = $this->load->language("extension/module/{$this->module_code}");
    $this->document->setTitle($this->language->get('heading_title'));

    if (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    $data['error_name'] = $this->language->get('error_name');
    $data['breadcrumbs'] = array();
    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
    );
    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_extension'),
      'href' => $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true)
    );
    if (!isset($this->request->get['module_id'])) {
      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link("extension/module/{$this->module_code}", 'token=' . $this->session->data['token'], true)
      );
    } else {
      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link("extension/module/{$this->module_code}", 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], true)
      );
    }

    $data['module_code'] = $this->module_code;
    $data['cancel'] = $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true);
    $data['token'] = $this->session->data['token'];
    $data['module_id'] = isset($this->request->get['module_id']) ? $this->request->get['module_id'] : 0;

    $this->load->model('localisation/language');
    $languages = $this->model_localisation_language->getLanguages();
    $data['languages'] = array();
    foreach ($languages as $language) {
      $data['languages'][] = array(
        'language_id' => $language['language_id'],
        'name' => $language['name'],
        'code' => $language['code'],
        'image' => $language['image']
      );
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view("extension/module/{$this->module_code}", $data));
  }

  protected function beforeIndex() {}

  public function load() {
    if (!isset($this->request->get['module_id'])) return;

    $this->load->model('extension/module');
    $module_info = $this->model_extension_module->getModule($this->request->get['module_id']);
    if (!$module_info) return;

    $this->jsonOutput(1, 'success', $module_info);
  }

  public function save() {
    $json = array();

    if ($this->request->server['REQUEST_METHOD'] !== 'POST') {
      $this->jsonOutput(0, 'REQUEST_METHOD Not allowed');
      return;
    }

    $this->language->load("extension/module/{$this->module_code}");

    $post_data = json_decode(file_get_contents('php://input'), true);
    if (empty($post_data['module'])) {
      $this->jsonOutput(0, 'No module data');
      return;
    }

    $module = $post_data['module'];
    if (!$this->validate($module)) {
      $this->jsonOutput(0, $this->language->get('error'), $this->error);
      return;
    }

    $this->load->model('extension/module');
    if (!isset($this->request->get['module_id']) || (int)$this->request->get['module_id'] <= 0) {
      $this->model_extension_module->addModule($this->module_code, $module);
    } else {
      $this->model_extension_module->editModule($this->request->get['module_id'], $module);
    }
    $this->jsonOutput(1, $this->language->get('text_success'));
  }

  protected function validate($module) {
    if (!$this->user->hasPermission('modify', "extension/module/{$this->module_code}")) {
      $this->error['message'] = $this->language->get('error_permission');
    }
    $this->validateForm($module);
    return !$this->error;
  }

  protected function validateForm($module) {
    if (!$this->validation_rules) return;

    foreach ($this->validation_rules as $key => $rawRules) {
      if (empty($key) || empty($rawRules)) continue;
      $rules = explode('|', $rawRules);
      if (empty($rules)) continue;
      foreach ($rules as $rule) {
        // Rule: required
        if ($rule == 'required') {
          if (!array_get($module, $key)) {
            $this->error[$key] = $this->language->get("error_{$key}");
            return;
          }
        }

        // Rule: min:x
        if (strpos($rule, 'min:') === 0) {
          $length = (int)str_replace('min:', '', $rule);
          if (strlen($module[$key]) < $length) {
            $this->error[$key] = $this->language->get("error_{$key}");
            return;
          }
        }

        // Rule: max:x
        if (strpos($rule, 'max:') === 0) {
          $length = (int)str_replace('max:', '', $rule);
          if (strlen($module[$key]) > $length) {
            $this->error[$key] = $this->language->get("error_{$key}");
            return;
          }
        }
      }
    }
  }

  public function thumb() {
    if(empty($this->request->get['image'])) {
      $image = '';
    } else {
      $image = rawurldecode($this->request->get['image']);
    }

    $this->load->model('tool/image');
    if ($image && is_file(DIR_IMAGE . $image)) {
      $image = $this->model_tool_image->resize($image, 100, 100);
    } else {
      $image = $this->model_tool_image->resize('placeholder.png', 100, 100);
    }

    $this->response->redirect($image);
  }

  protected function jsonOutput($status, $message = '', $data = null) {
    $json = array();
    $json['status'] = (int)$status;
    $json['message'] = $message;

    if ($data) {
      $json['data'] = $data;
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }
}
